<template>
  <div class="course-detail">
    <el-card v-loading="loading">
      <template #header>
        <div class="header">
          <el-button @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <span>课程详情</span>
          <div></div>
        </div>
      </template>
      
      <div v-if="course" class="detail-content">
        <!-- 课程基本信息 -->
        <div class="course-info">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-image 
                v-if="course.cover" 
                :src="coverUrl" 
                fit="cover"
                class="course-cover"
              />
              <div v-else class="no-cover">暂无封面</div>
            </el-col>
            <el-col :span="16">
              <h2>{{ course.title }}</h2>
              <div class="course-meta">
                <el-tag type="danger" size="large" class="price-tag">
                  ¥{{ (course.price / 100).toFixed(2) }}
                </el-tag>
                <el-tag type="info" size="large">
                  已预订: {{ course.bookNum || 0 }}人
                </el-tag>
              </div>
              <div class="course-desc">
                <h3>课程介绍</h3>
                <p>{{ course.desc }}</p>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 课程章节列表 -->
        <el-divider />
        <div class="course-categories">
          <div class="categories-header">
            <h3>课程章节</h3>
            <el-button type="primary" @click="handleAddCategory" v-if="userType == 9">
              <el-icon><Plus /></el-icon>
              新增章节
            </el-button>
          </div>
          <el-table 
            :data="categories" 
            style="width: 100%"
            :show-header="true"
          >
            <el-table-column prop="code" label="章节代码" width="120" />
            <el-table-column prop="name" label="章节名称" />
            <el-table-column prop="content" label="内容" width="180" />
            <el-table-column prop="sort_order" label="排序" width="80" />
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <el-button 
                  v-if="scope.row.can_view && scope.row.url" 
                  type="primary" 
                  text
                  @click="playVideo(scope.row)"
                >
                  <el-icon><VideoPlay /></el-icon>
                  播放
                </el-button>
                <el-button 
                  v-if="userType == 9"
                  type="primary" 
                  text
                  @click="handleEditCategory(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  v-if="userType == 9"
                  type="danger" 
                  text
                  @click="handleDeleteCategory(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
    
    <!-- 视频播放对话框 -->
    <el-dialog
      v-model="videoDialogVisible"
      :title="currentVideo?.name || '视频播放'"
      width="80%"
      @close="stopVideo"
    >
      <div class="video-container">
        <video 
          ref="videoPlayer"
          :src="currentVideo?.url"
          controls
          autoplay
          style="width: 100%; max-height: 70vh;"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
    </el-dialog>
    
    <!-- 章节编辑对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="categoryDialogType === 'add' ? '新增章节' : '编辑章节'"
      width="600px"
    >
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="categoryFormRules" label-width="100px">
        <el-form-item label="章节代码" prop="code">
          <el-input v-model="categoryForm.code" placeholder="请输入章节代码，如：cat_01"/>
        </el-form-item>
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入章节名称，如：01. 导学"/>
        </el-form-item>
        <el-form-item label="内容描述" prop="content">
          <el-input v-model="categoryForm.content" placeholder="请输入内容描述，如：视频|25分钟45秒"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="categoryForm.sort_order" :min="1" placeholder="请输入排序序号"/>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            提示：排序为1的章节默认可观看，其他章节默认不可观看
          </div>
        </el-form-item>
        <el-form-item label="视频文件">
          <el-upload
            v-model:file-list="videoList"
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            accept=".mp4,.avi,.mov,.wmv,.flv,.mkv"
            :on-change="handleVideoChange"
          >
            <el-button type="primary">点击选择视频</el-button>
          </el-upload>
          <div v-if="currentVideoUrl" style="margin-top: 10px; color: #409eff;">
            当前视频：{{ currentVideoUrl }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCategorySubmit" :loading="categorySubmitting">
            {{ categorySubmitting ? '保存中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, VideoPlay, Lock, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/user'
import { STATIC_RESOURCE_URL } from '../../config'
import api from '../../api'

export default {
  name: 'CourseDetail',
  components: {
    ArrowLeft,
    VideoPlay,
    Lock,
    Plus,
    Edit,
    Delete
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    const loading = ref(false)
    const course = ref(null)
    const categories = ref([])
    const videoDialogVisible = ref(false)
    const currentVideo = ref(null)
    const videoPlayer = ref(null)
    const userType = ref(0)
    const coverUrl = ref('')
    
    // 章节对话框相关
    const categoryDialogVisible = ref(false)
    const categoryDialogType = ref('add')
    const categorySubmitting = ref(false)
    const categoryFormRef = ref(null)
    const videoList = ref([])
    const currentVideoUrl = ref('')
    
    const categoryForm = reactive({
      id: null,
      code: '',
      name: '',
      content: '',
      url: '',
      sort_order: 1
    })
    
    const categoryFormRules = {
      code: [
        { required: true, message: '请输入章节代码', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入章节名称', trigger: 'blur' }
      ],
      sort_order: [
        { required: true, message: '请输入排序序号', trigger: 'blur' }
      ]
    }
    
    // 处理视频文件变化
    const handleVideoChange = (file) => {
      // 视频文件变化处理
    }
    
    // 加载课程详情
    const loadCourseDetail = async () => {
      const courseId = route.params.id
      if (!courseId) {
        ElMessage.error('课程ID不存在')
        goBack()
        return
      }
      
      loading.value = true
      userType.value = userStore.user?.category
      try {
        const response = await api.get(`/chance/courses/${courseId}`)
        course.value = response
        const cover = response.cover
        coverUrl.value = cover.startsWith('http') ? cover: `${STATIC_RESOURCE_URL}${cover}`
        // 同时加载章节列表（用于管理）
        await loadCategories()
      } catch (error) {
        ElMessage.error('获取课程详情失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
    
    // 加载章节列表
    const loadCategories = async () => {
      const courseId = route.params.id
      try {
        const response = await api.get(`/chance/courses/${courseId}/categories`)
        categories.value = response
      } catch (error) {
        console.error('获取章节列表失败', error)
      }
    }
    
    // 返回列表
    const goBack = () => {
      router.push('/courses')
    }
    
    // 播放视频
    const playVideo = (category) => {
      // 如果URL不是完整的HTTP地址，添加静态资源前缀
      const videoUrl = category.url.startsWith('http') 
        ? category.url 
        : `${STATIC_RESOURCE_URL}${category.url}`
      
      currentVideo.value = {
        ...category,
        url: videoUrl
      }
      videoDialogVisible.value = true
    }
    
    // 停止视频
    const stopVideo = () => {
      if (videoPlayer.value) {
        videoPlayer.value.pause()
      }
      currentVideo.value = null
    }
    
    // 新增章节
    const handleAddCategory = () => {
      categoryDialogType.value = 'add'
      // 重置表单
      if (categoryFormRef.value) {
        categoryFormRef.value.resetFields()
      }
      categoryForm.id = null
      categoryForm.code = ''
      categoryForm.name = ''
      categoryForm.content = ''
      categoryForm.url = ''
      categoryForm.sort_order = categories.value.length + 1
      videoList.value = []
      currentVideoUrl.value = ''
      categoryDialogVisible.value = true
    }
    
    // 编辑章节
    const handleEditCategory = (category) => {
      categoryDialogType.value = 'edit'
      categoryForm.id = category.id
      categoryForm.code = category.code
      categoryForm.name = category.name
      categoryForm.content = category.content || ''
      categoryForm.url = category.url || ''
      categoryForm.sort_order = category.sort_order
      videoList.value = []
      // 显示当前视频URL
      if (category.url) {
        currentVideoUrl.value = category.url
      } else {
        currentVideoUrl.value = ''
      }
      categoryDialogVisible.value = true
    }
    
    // 删除章节
    const handleDeleteCategory = async (category) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除章节"${category.name}"吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const courseId = route.params.id
        await api.delete(`/chance/courses/${courseId}/categories/${category.id}`)
        ElMessage.success('章节删除成功')
        await loadCategories()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('章节删除失败')
        }
      }
    }
    
    // 提交章节表单
    const handleCategorySubmit = async () => {
      try {
        categorySubmitting.value = true
        await categoryFormRef.value.validate(async (valid) => {
          if (valid) {
            try {
              const courseId = route.params.id
              const formData = new FormData()
              formData.append('code', categoryForm.code)
              formData.append('name', categoryForm.name)
              formData.append('content', categoryForm.content)
              formData.append('sort_order', categoryForm.sort_order)
              
              // 添加视频文件（如果有新选择）
              if (videoList.value.length > 0) {
                formData.append('video', videoList.value[0].raw)
              }
              
              if (categoryDialogType.value === 'add') {
                await api.post(`/chance/courses/${courseId}/categories`, formData)
                ElMessage.success('章节添加成功')
              } else {
                await api.put(`/chance/courses/${courseId}/categories/${categoryForm.id}`, formData)
                ElMessage.success('章节更新成功')
              }
              
              categoryDialogVisible.value = false
              await loadCategories()
            } catch (error) {
              ElMessage.error(categoryDialogType.value === 'add' ? '章节添加失败' : '章节更新失败')
            }
          }
        })
      } finally {
        categorySubmitting.value = false
      }
    }
    
    onMounted(() => {
      loadCourseDetail()
    })
    
    return {
      loading,
      course,
      categories,
      coverUrl,
      videoDialogVisible,
      currentVideo,
      videoPlayer,
      userType,
      categoryDialogVisible,
      categoryDialogType,
      categorySubmitting,
      categoryFormRef,
      categoryForm,
      categoryFormRules,
      videoList,
      currentVideoUrl,
      goBack,
      playVideo,
      stopVideo,
      handleAddCategory,
      handleEditCategory,
      handleDeleteCategory,
      handleCategorySubmit,
      handleVideoChange
    }
  }
}
</script>

<style scoped>
.course-detail {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  padding: 20px;
}

.course-info {
  margin-bottom: 30px;
}

.course-cover {
  width: 100%;
  height: 300px;
  border-radius: 8px;
}

.no-cover {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  color: #909399;
  font-size: 16px;
}

.course-meta {
  margin: 20px 0;
  display: flex;
  gap: 15px;
}

.price-tag {
  font-size: 24px;
  padding: 10px 20px;
  font-weight: bold;
}

.course-desc {
  margin-top: 20px;
}

.course-desc h3 {
  margin-bottom: 10px;
  color: #303133;
}

.course-desc p {
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
}

.course-categories {
  margin-top: 20px;
}

.categories-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.categories-header h3 {
  margin: 0;
  color: #303133;
}

.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #000;
}
</style>
